package com.service;

import com.dao.BookDao;
import com.model.Book;
import com.util.DBUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BookService {

    public List<Book> listBooks(){
        Connection connection = DBUtil.getConnection();
        BookDao bookDao = new BookDao();
        List<Book> books = null;

        try {
            books = bookDao.listBooks(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DBUtil.closeResource(connection,null,null);
        return books;
    }
    public List<Book> searchBookByName(String name){
        Connection connection = DBUtil.getConnection();
        BookDao bookDao = new BookDao();
        List<Book> books = null;

        try {
            books = bookDao.searchBook(connection,name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DBUtil.closeResource(connection,null,null);
        return books;
    }
    public boolean addBook(Book book){
        boolean flag=false;
        Connection connection = DBUtil.getConnection();
        BookDao bookDao = new BookDao();

        try {
            bookDao.addBook(connection, book);
            flag=true;
        } catch (SQLException e) {
            e.printStackTrace();
            flag=false;
        }

        DBUtil.closeResource(connection,null,null);
        return flag;
    }
    public boolean updateBook(Book book){
        boolean flag=false;
        Connection connection = DBUtil.getConnection();
        BookDao bookDao = new BookDao();

        try {
            bookDao.updateBook(connection, book);
            flag=true;
        } catch (SQLException e) {
            e.printStackTrace();
            flag=false;
        }

        DBUtil.closeResource(connection,null,null);
        return flag;
    }
    public boolean deleteBookById(int id){
        boolean flag=false;
        Connection connection = DBUtil.getConnection();
        BookDao bookDao = new BookDao();
        try {
            int updateRows = bookDao.deleteBookById(connection, id);
            if (updateRows>0){
                flag=true;
            }

        } catch (SQLException e) {
            e.printStackTrace();
            flag=false;
        }

        DBUtil.closeResource(connection,null,null);
        return flag;
    }
    public boolean addRelation( int authorId, int bookId){
        boolean flag=false;
        Connection connection = DBUtil.getConnection();
        BookDao bookDao = new BookDao();

        try {
            bookDao.addRelation(connection, authorId, bookId);
            flag=true;
        } catch (SQLException e) {
            e.printStackTrace();
            flag=false;
        }

        DBUtil.closeResource(connection,null,null);
        return flag;
    }
}
